<template>
  <AdminLayout title="产品变体管理" subtitle="管理产品的规格变体">
    <template #actions>
      <Link :href="route('admin.products.index')" 
            class="inline-flex items-center px-4 py-2 border border-gray-300 text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 transition-colors duration-200">
        <svg class="-ml-1 mr-2 h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
        </svg>
        返回产品列表
      </Link>
    </template>

    <!-- 产品信息 -->
    <div class="bg-white shadow-sm rounded-lg mb-6">
      <div class="px-6 py-4 border-b border-gray-200">
        <h3 class="text-lg font-medium text-gray-900">产品信息</h3>
      </div>
      <div class="px-6 py-4">
        <div class="flex items-center space-x-4">
          <img v-if="product.images && product.images.length > 0" 
               :src="product.images[0].url" 
               :alt="product.name"
               class="h-16 w-16 object-cover rounded-lg"
          />
          <div v-else class="h-16 w-16 bg-gray-200 rounded-lg flex items-center justify-center">
            <svg class="h-8 w-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
          </div>
          <div>
            <h4 class="text-lg font-medium text-gray-900">{{ product.name }}</h4>
            <p class="text-sm text-gray-500">{{ product.description || '暂无描述' }}</p>
            <div class="mt-1 flex items-center space-x-4">
              <span class="text-sm font-medium text-gray-900">
                ¥{{ formatPrice(product.price) }}
              </span>
              <span v-if="product.compare_price" class="text-sm text-gray-500 line-through">
                ¥{{ formatPrice(product.compare_price) }}
              </span>
              <span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium"
                    :class="product.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
                {{ product.is_active ? '已启用' : '已禁用' }}
              </span>
              <span v-if="product.is_featured" class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-blue-100 text-blue-800">
                推荐
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 变体列表 -->
    <div class="bg-white shadow-sm rounded-lg">
      <div class="px-6 py-4 border-b border-gray-200">
        <div class="flex items-center justify-between">
          <h3 class="text-lg font-medium text-gray-900">规格变体</h3>
          <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800">
            {{ variants.length }} 个变体
          </span>
        </div>
      </div>
      
      <div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
          <thead class="bg-gray-50">
            <tr>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                SKU
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                规格信息
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                价格
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                库存
              </th>
              <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                状态
              </th>
              <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
                操作
              </th>
            </tr>
          </thead>
          <tbody class="bg-white divide-y divide-gray-200">
            <tr v-for="variant in variants" :key="variant.id" class="hover:bg-gray-50">
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm font-medium text-gray-900">
                  {{ variant.sku }}
                </div>
              </td>
              <td class="px-6 py-4">
                <div class="flex flex-wrap gap-2">
                  <span v-for="spec in variant.specifications" :key="spec.id" 
                        class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                    {{ spec.attribute_name }}: {{ spec.display_value || spec.value }}
                  </span>
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">
                  ¥{{ formatPrice(variant.price) }}
                </div>
                <div v-if="variant.compare_price && variant.compare_price !== variant.price" 
                     class="text-sm text-gray-500 line-through">
                  ¥{{ formatPrice(variant.compare_price) }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <div class="text-sm text-gray-900">
                  {{ variant.stock_quantity }}
                </div>
              </td>
              <td class="px-6 py-4 whitespace-nowrap">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium"
                      :class="variant.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
                  {{ variant.is_active ? '启用' : '禁用' }}
                </span>
              </td>
              <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                <div class="flex items-center justify-end space-x-2">
                  <button @click="editVariant(variant)" 
                          class="text-gray-600 hover:text-gray-900 transition-colors duration-200">
                    编辑
                  </button>
                  <button @click="toggleVariantStatus(variant)" 
                          class="text-blue-600 hover:text-blue-900 transition-colors duration-200">
                    {{ variant.is_active ? '禁用' : '启用' }}
                  </button>
                  <button @click="deleteVariant(variant)" 
                          class="text-red-600 hover:text-red-900 transition-colors duration-200">
                    删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 空状态 -->
      <div v-if="variants.length === 0" class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">暂无变体</h3>
        <p class="mt-1 text-sm text-gray-500">该产品还没有规格变体</p>
      </div>
    </div>

    <!-- 编辑变体对话框 -->
    <div v-if="showEditDialog" class="fixed inset-0 z-50 overflow-y-auto">
      <div class="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
        <div class="fixed inset-0 bg-gray-500 bg-opacity-75 transition-opacity" @click="closeEditDialog"></div>
        
        <div class="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
          <form @submit.prevent="updateVariant">
            <div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
              <div class="sm:flex sm:items-start">
                <div class="mt-3 text-center sm:mt-0 sm:text-left w-full">
                  <h3 class="text-lg leading-6 font-medium text-gray-900 mb-4">
                    编辑规格型号
                  </h3>
                  
                  <div class="space-y-4">
                    <!-- SKU -->
                    <div>
                      <label class="block text-sm font-medium text-gray-700">SKU</label>
                      <input 
                        v-model="editingVariant.sku"
                        type="text" 
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        required
                      />
                    </div>
                    
                    <!-- 价格 -->
                    <div class="grid grid-cols-2 gap-4">
                      <div>
                        <label class="block text-sm font-medium text-gray-700">售价</label>
                        <input 
                          v-model.number="editingVariant.price"
                          type="number" 
                          step="0.01"
                          min="0"
                          class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                          required
                        />
                      </div>
                      <div>
                        <label class="block text-sm font-medium text-gray-700">原价</label>
                        <input 
                          v-model.number="editingVariant.compare_price"
                          type="number" 
                          step="0.01"
                          min="0"
                          class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        />
                      </div>
                    </div>
                    
                    <!-- 库存 -->
                    <div>
                      <label class="block text-sm font-medium text-gray-700">库存数量</label>
                      <input 
                        v-model.number="editingVariant.stock_quantity"
                        type="number" 
                        min="0"
                        class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-gray-900 focus:border-gray-900 sm:text-sm"
                        required
                      />
                    </div>
                    
                    <!-- 规格信息 -->
                    <div>
                      <label class="block text-sm font-medium text-gray-700">规格信息</label>
                      <div class="mt-2 space-y-3">
                        <div v-for="spec in editingVariant.specifications" :key="spec.id" 
                             class="flex items-center space-x-3">
                          <span class="text-sm text-gray-600 w-24 flex-shrink-0">{{ spec.attribute_name }}:</span>
                          <div class="flex-1">
                            <input 
                              :value="spec.display_value"
                              type="text" 
                              readonly
                              class="border-gray-300 rounded-md shadow-sm bg-gray-50 text-gray-500 cursor-not-allowed sm:text-sm w-full"
                            />
                          </div>
                        </div>
                      </div>
                      <p class="mt-2 text-sm text-gray-500">规格信息不可修改，如需修改请联系系统管理员</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
              <button 
                type="submit"
                :disabled="updating"
                class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-gray-900 text-base font-medium text-white hover:bg-gray-800 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-50 disabled:cursor-not-allowed"
              >
                {{ updating ? '更新中...' : '更新规格型号' }}
              </button>
              <button 
                type="button"
                @click="closeEditDialog"
                class="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-900 sm:mt-0 sm:ml-3 sm:w-auto sm:text-sm"
              >
                取消
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </AdminLayout>
</template>

<script setup>
import { ref } from 'vue'
import { Link, router } from '@inertiajs/vue3'
import AdminLayout from '@/Layouts/AdminLayout.vue'
import { useNotification } from '@/composables/useNotification'

const props = defineProps({
  product: {
    type: Object,
    required: true
  },
  variants: {
    type: Array,
    required: true
  }
})

// 通知功能
const { showSuccess, showError } = useNotification()

// 编辑对话框状态
const showEditDialog = ref(false)
const editingVariant = ref({})
const updating = ref(false)

const formatPrice = (price) => {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(price)
}

const editVariant = (variant) => {
  editingVariant.value = { ...variant }
  showEditDialog.value = true
}

const closeEditDialog = () => {
  showEditDialog.value = false
  editingVariant.value = {}
}

const updateVariant = () => {
  updating.value = true
  
  router.put(route('admin.variants.update', editingVariant.value.id), {
    sku: editingVariant.value.sku,
    price: editingVariant.value.price,
    compare_price: editingVariant.value.compare_price,
    stock_quantity: editingVariant.value.stock_quantity,
  }, {
    onSuccess: () => {
      // 后端已经发送了 flash 消息，这里不需要重复显示
      closeEditDialog()
    },
    onError: () => {
      showError('更新失败', '规格型号信息更新失败，请重试')
    },
    onFinish: () => {
      updating.value = false
    }
  })
}

const toggleVariantStatus = (variant) => {
  router.post(route('admin.variants.toggle-status', variant.id), {}, {
    onSuccess: () => {
      // 后端已经发送了 flash 消息，这里不需要重复显示
    },
    onError: () => {
      showError('操作失败', '状态切换失败，请重试')
    }
  })
}

const deleteVariant = (variant) => {
  if (confirm(`确定要删除规格型号 "${variant.sku}" 吗？此操作不可恢复！`)) {
    router.delete(route('admin.variants.destroy', variant.id), {
      onSuccess: () => {
        // 后端已经发送了 flash 消息，这里不需要重复显示
      },
      onError: () => {
        showError('删除失败', '删除规格型号失败，请重试')
      }
    })
  }
}
</script>
